module.exports = options => {
    const jwt = require('jsonwebtoken')
    const User = require('../models/user')
    const response = require('../utils/response')
    return async(req, res, next) => {
        // 获取token 
        const token = String(req.headers.authorization || '').split(' ').pop()
        if (!token) return response(res,422,'您未登录,请先登录~~',null)
            // token校验
        const {id,expiresIn,ctime} = jwt.verify(token, req.app.get('token'))
        //获取当前时间
        const nowTime = parseInt(new Date().getTime() / 1000)
        //过期时间
        const exp = ctime + expiresIn
        let cha = exp - nowTime
        if (cha < 0) return response(res, 401, 'token过期~~', null)

        const tokenUser = await User.findById(id)
        if (!tokenUser) return response(res, 402, '无效token~~', null)
        await next()
    }
}